package com.atguigui.leetcode;

/**
 * 875.爱吃香蕉的珂珂
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/6/7 21:08
 */
public class P875KokoEatingBananas {
    public static void main(String[] args) {
        Solution solution = new P875KokoEatingBananas().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minEatingSpeed(int[] piles, int h) {
            int low = 1;
            int high = 0;
            //找到最高香蕉数
            for (int pile : piles) {
                high = Math.max(high, pile);
            }

            int k = high;
            while (low < high) {
                //二分查找最小吃香蕉的速度
                int speed = (high - low) / 2 + low;
                long time = getTime(piles, speed);
                if (time <= h) {
                    //满足条件的不断迭代
                    k = speed;
                    high = speed;
                } else {
                    // 不满足条件的吃香蕉速度增加1
                    low = speed + 1;
                }
            }

            return k;
        }

        /**
         * 计算吃掉这堆香蕉的总共时间
         *
         * @param piles 一堆香蕉
         * @param speed 吃香蕉的速度
         * @return
         */
        public long getTime(int[] piles, int speed) {
            long time = 0;
            for (int pile : piles) {
                int curTime = (pile + speed - 1) / speed;
                time += curTime;
            }
            return time;
        }

    }
}
